package com.pf.controller;

import com.pf.dto.ResultResp;
import com.pf.utils.RedisUtils;
import com.pf.utils.ResultRespUtils;
import com.pf.utils.ShortUrlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/12/8 23:17
 */
@RestController
public class ShortUrlController {


    /**
     * 生成短链接
     * <p>
     * 访问示例：
     * <p>
     * http://localhost:8080/short/url/generate?longUrl=https://blog.csdn.net/weixin_43113679/article/details/90085175
     *
     * @param longUrl
     * @return
     */
    @GetMapping("/short/url/generate")
    public ResultResp<String> generateShortUrl(@RequestParam("longUrl") String longUrl) {
        String[] shortCodes = ShortUrlUtils.generateShortUrl(longUrl);
        String shortCode = shortCodes[0];
        RedisUtils.set("short-url-" + shortCode, longUrl, 60);
        String shortUrl = "http://localhost:8080/" + shortCode;
        return ResultRespUtils.success(shortUrl);
    }

    /**
     * 访问短链接，重定向到对应长链接
     * <p>
     * 访问示例
     * http://localhost:8080/Rz67Jj
     *
     * @param shortCode
     * @param response
     */
    @GetMapping("/{shortCode}")
    public void redirectLongUrl(@PathVariable("shortCode") String shortCode,
                                HttpServletResponse response) {
        String longUrl = RedisUtils.get("short-url-" + shortCode, String.class);
        if (StringUtils.isBlank(longUrl)) {
            try {
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.print("404：找不到该页面");
                writer.flush();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            try {
                response.sendRedirect(longUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
